<template>
	<view class="container">
		<wjf-stat-breadcrumb :routes="routes"></wjf-stat-breadcrumb>
		<view class="content-box">
			<uni-forms ref="form" :value="formData" :label-position="labelPosition" :label-width="90"
				validateTrigger="bind">
				<uni-forms-item class="align-items-center" name="organization" :label="$w('机构或公司')" required>
					<uni-easyinput :placeholder="$w('输入您的机构或公司名称')" v-model="formData.organization" focus
						@input="inputOrganization" />
				</uni-forms-item>
				<uni-forms-item class="align-items-center" name="position" :label="$w('职务')">
					<uni-easyinput :placeholder="$w('输入您的职务')" v-model="formData.position" />
				</uni-forms-item>
				<uni-forms-item class="align-items-center" name="realname" :label="$w('姓名')" required>
					<uni-easyinput :placeholder="$w('输入您的姓名')" v-model="formData.realname" @input="inputRealName" />
				</uni-forms-item>
				<uni-forms-item class="align-items-center" name="gender" :label="$w('性别')">
					<uv-radio-group v-model="formData.gender">
						<uv-radio :customStyle="{margin: '8px'}" v-for="(item, index) in gendersList" :key="index"
							:label="item.text" :name="item.text">
						</uv-radio>
					</uv-radio-group>

				</uni-forms-item>
				<uni-forms-item class="align-items-center" name="email" :label="$w('邮箱')">
					<uni-easyinput :placeholder="$w('输入您的email')" v-model="formData.email" />
				</uni-forms-item>
				<uni-forms-item class="align-items-center" name="mobile" :label="$w('手机号码')" required>
					<view class="phone-input">
						<view class="country-code" @click="toggleDropdown">
							+{{ selectedCode }} <text>▼</text>
						</view>
						<uni-easyinput :placeholder="$w('输入您的手机号码')" v-model="formData.mobile" />
					</view>
					<view v-if="dropdownVisible" class="dropdown">
						<view v-for="(code, index) in codes" :key="index" @click="selectCode(code)"
							class="dropdown-item">
							+{{ code }}
						</view>
					</view>
				</uni-forms-item>
			</uni-forms>
			<view class="button-group">
				<navigator open-type="navigateBack" style="margin-left: 30px;">
					<button class="button-style" size="mini">{{$w('返回')}}</button>
				</navigator>
				<button class="button-style" size="mini" style="color: #fff;background-color: dodgerblue;"
					@click="nextRegistration">{{$w('继续报名')}}</button>
				<button class="button-style" size="mini" style="color: #fff;background-color: dodgerblue;"
					@click="submit">{{$w('提交')}}</button>
			</view>
		</view>
		<!-- <view class="">
			<button type="default" @click="test">test</button>
		</view> -->
		<uv-modal ref="modal" :title="$w('提示')" :content='$w("已经报名了,　请勿重复提交。")' :confirmText="$w('修改报名信息')"
			showCancelButton :cancelText="$w('取消')"></uv-modal>
	</view>
</template>

<script>
	import {
		validator
	} from '@/js_sdk/validator/tian-event-registration.js';

	function getValidator(fields) {
		let reuslt = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				reuslt[key] = validator[key]
			}
		}
		return reuslt
	}
	const db = uniCloud.database()
	import message from './i18n/index.js'
	const $w = (key) => {
		return message[uni.getLocale()][key]
	}
	export default {
		data() {
			return {
				screenWidth: 0,
				event_id: '',
				formData: {
					realname: '',
					gender: $w("不填"),
					email: '',
					mobile: '',
					organization: '', //输入的原始名称 后台进行翻译
					position: '' //职务
				},
				countries: ['中国', '哈萨克斯坦', '吉尔吉斯斯坦'],
				codes: ['86', '7', '996'],
				selectedCode: '86', // 默认选择中国区号
				phoneNumber: '',
				dropdownVisible: false, // 控制下拉框的显示
				rules: {
					...getValidator(["realname", "email", "mobile", "mobile_area_code", "organization"])
				}
			}
		},
		computed: {
			locaLang() {
				return uni.getLocale()
			},
			$w() {
				return $w
			},
			userInfo() {
				return this.$store.state.user.userInfo
			},
			labelPosition() {
				return this.screenWidth > 768 ? 'left' : 'top'
			},
			routes() {
				return [{
						to: "/pages/expo-forum/expo-forum",
						name: this.$w("展会活动"),
					},
					{
						to: "/pages/expo-forum/event-detail?id=" + this.event_id,
						name: this.$w("活动详情"),
					},
					{
						to: "",
						name: this.$w("当前页"),
					}
				]
			},
			gendersList() {
				return [{
					"text": $w("不填"),
					"value": 0
				}, {
					"text": $w("男"),
					"value": 1
				}, {
					"text": $w("女"),
					"value": 2
				}]
			}
		},
		onLoad(e) {
			this.event_id = e.id
			console.log(this.event_id);
		},
		onReady() {
			this.updateScreenWidth();
			uni.onWindowResize(this.updateScreenWidth);
			this.$refs.form.setRules(this.rules)
		},
		beforeDestroy() {
			uni.offWindowResize(this.updateScreenWidth); // 组件销毁时移除监听
		},
		methods: {
			test() {
				const wjfObj = uniCloud.importObject('wjf-co')
				wjfObj.eventRegistration().then(res => {
					console.log(res);
				})
			},
			inputRealName(e) {
				// setTimeout(() => {
				// 	Object.keys(this.formData.real_name).forEach(lang => {
				// 		if (lang != this.locaLang) {
				// 			this.formData.real_name[lang] = e
				// 		}
				// 	})
				// })
			},
			inputOrganization(e) {
				// setTimeout(() => {
				// 	Object.keys(this.formData.organization).forEach(lang => {
				// 		if (lang != this.locaLang) {
				// 			this.formData.organization[lang] = e
				// 		}
				// 	})
				// })
			},
			//多次报名
			nextRegistration() {
				this.formData.realname = ''
				this.formData.email = ''
				this.formData.mobile = ''
				this.formData.position = ''
				this.formData.gender = this.$w('不填')
			},

			/**
			 * 触发表单提交
			 */
			async submit() {
				this.$refs.form.validate().then((res) => {
					/**
					 * 追加一些默认数据
					 * 注意 后期应再加上如有店铺 店铺id
					 */
					let userPara = {
						country_code: this.selectedCode,
						gender: this.gendersList.filter(item => item.text == res.gender)[0].value,
						lang: this.locaLang,
						event_id: this.event_id,
						registration_date: Date.now()
					}
					let data = Object.assign(res, userPara)
					console.log(res);
					this.submitForm(data)
				})
			},
			uplicateSubmit() {
				this.$refs.modal.open()
			},
			submitForm(value) {
				const wjfObj = uniCloud.importObject('wjf-co', {
					loadingOptions: {
						title: '' // 只保留转圈状态
					}
				})
				wjfObj.eventRegistration(value).then(res => {
					// console.log(res);
					if (res.errMsg == this.$w('重复提交报名数据')) {
						this.uplicateSubmit()
					} else {
						uni.showToast({
							title: this.$w('提交成功！')
						})
					}

				})
			},
			submitForm_1(value) {
				uni.showLoading({
					mask: true
				})
				db.collection('tian-event-registration').add(value).then((res) => {
					uni.showToast({
						title: '提交成功！'
					})
					// this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || ('请求服务失败'),
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			toggleDropdown() {
				console.log(123);
				this.dropdownVisible = !this.dropdownVisible; // 切换下拉框的可见性
			},
			selectCode(code) {
				this.selectedCode = code; // 设置选择的区号
				this.dropdownVisible = false; // 选择后隐藏下拉框
			},
			// 获取屏幕宽度
			updateScreenWidth() {
				uni.getSystemInfo({
					success: (res) => {
						this.screenWidth = res.windowWidth; // 更新屏幕宽度
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.container {
		max-width: 800px;
		height: 100vh;
		/* 设置最大宽度 */
		margin: 0 auto;
		/* 居中显示 */
		// padding: 20px;
		/* 添加内边距（可选） */
		background-color: #fff;
	}

	.content-box {
		margin: 15px;
	}

	.button-group {
		margin-top: 60px;
		display: flex;
		justify-content: center;

		// .button-style {
		// 	height: 40rpx;
		// 	display: flex;
		// 	justify-content: center;
		// 	align-items: center;
		// 	font-size: 30rpx;
		// }
	}

	.phone-input {
		display: flex;
		align-items: center;
	}

	.country-code {
		// padding: 10px;
		// border: 1px solid #ccc;
		cursor: pointer;
		margin-right: 6rpx;
	}

	.dropdown {
		position: absolute;
		border: 1px solid #ccc;
		border-radius: 4rpx;
		background: white;
		z-index: 1000;
		width: 100rpx;
		/* 根据需要调整宽度 */
	}

	.dropdown-item {
		padding: 10rpx;
		cursor: pointer;
	}

	.dropdown-item:hover {
		background: #f0f0f0;
		/* 鼠标悬停时的效果 */
	}
</style>